<template>
  <div class="question-header">
    <h3>题目 {{ questionIndex + 1 }}</h3>
    <div class="header-actions">
      <el-button v-if="questionIndex === 0" link type="primary" @click="$emit('add-question')">
        <el-icon><Plus /></el-icon>新增题目
      </el-button>
      <el-button link type="danger" @click="$emit('remove-question')"> 删除此题 </el-button>
    </div>
  </div>

  <el-form-item
    :error="errors.title"
    :validate-status="errors.title ? 'error' : ''"
    class="required-label"
    label="题目名称"
    prop="title"
  >
    <el-input
      :model-value="judgeForms[questionIndex].title"
      :rows="2"
      placeholder="请输入题目名称"
      type="textarea"
      @update:model-value="(val) => handleUpdateForm('title', val)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.options"
    :validate-status="errors.options ? 'error' : ''"
    class="required-label"
    label="题目选项"
  >
    <div class="options-container">
      <div
        v-for="(option, index) in judgeForms[questionIndex].options"
        :key="index"
        class="option-item"
      >
        <div class="option-content">
          <div class="option-label">{{ option.key }}</div>
          <el-input
            :model-value="option.value"
            :status="errors[`option${index}`] ? 'error' : ''"
            disabled
            placeholder="请输入选项内容"
          />
        </div>
      </div>
    </div>
  </el-form-item>

  <el-form-item
    :error="errors.answer"
    :validate-status="errors.answer ? 'error' : ''"
    class="required-label"
    label="正确答案"
    prop="answer"
  >
    <el-radio-group
      :model-value="judgeForms[questionIndex].answer"
      @update:model-value="(val) => handleUpdateForm('answer', val)"
    >
      <el-radio
        v-for="option in judgeForms[questionIndex].options"
        :key="option.key"
        :value="option.key"
      >
        {{ option.value }}
      </el-radio>
    </el-radio-group>
  </el-form-item>

  <el-form-item label="答案解析" prop="analysis">
    <el-input
      :model-value="judgeForms[questionIndex].analysis"
      :rows="3"
      placeholder="请输入答案解析"
      type="textarea"
      @update:model-value="handleUpdateForm('analysis', $event)"
    />
  </el-form-item>

  <el-form-item
    :error="errors.difficulty"
    :validate-status="errors.difficulty ? 'error' : ''"
    class="required-label"
    label="难度系数"
    prop="difficulty"
  >
    <el-radio-group
      :model-value="judgeForms[questionIndex].difficulty"
      @update:model-value="(val) => handleUpdateForm('difficulty', val)"
    >
      <el-radio :value="1">简单</el-radio>
      <el-radio :value="2">中等</el-radio>
      <el-radio :value="3">困难</el-radio>
    </el-radio-group>
  </el-form-item>

  <el-form-item label="题目分类" prop="classId">
    <class-select
      v-model="judgeForms[questionIndex].classId"
      :type="2"
      placeholder="请选择题目分类(选填)"
      @change="(val) => handleUpdateForm('classId', val)"
    />
  </el-form-item>
</template>

<script lang="ts" setup>
import { Plus } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { storeToRefs } from 'pinia'
import { useQuestionStore } from '@/store/modules/material/question'
import ClassSelect from '../../compont/ClassSelect.vue'

const props = defineProps<{
  questionIndex: number
  tabName?: string
}>()

const questionStore = useQuestionStore()
const { judgeForms } = storeToRefs(questionStore)
const { updateJudgeForm } = questionStore

const errors = ref<Record<string, string>>({})

// 添加实时校验方法
const validateField = (field: string) => {
  const form = judgeForms.value[props.questionIndex]
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【判断题】-第${questionNumber}题：`

  errors.value = { ...errors.value }
  delete errors.value[field]

  switch (field) {
    case 'title':
      if (!form.title?.trim()) {
        errors.value.title = '请输入题目标题'
      }
      break
    case 'answer':
      if (!form.answer) {
        errors.value.answer = '请选择正确答案'
      }
      break
    case 'difficulty':
      if (!form.difficulty) {
        errors.value.difficulty = '请选择难度系数'
      }
      break
  }
}

// 修改更新表单的方法，添加实时校验
const handleUpdateForm = (field: string, value: any) => {
  updateJudgeForm(props.questionIndex, field, value)
  validateField(field)
}

// 校验方法
const validate = () => {
  const errorMessages: string[] = []
  errors.value = {}
  const questionNumber = props.questionIndex + 1
  const tabPrefix = `【判断题】-第${questionNumber}题：`

  if (!judgeForms.value[props.questionIndex].title?.trim()) {
    errorMessages.push(`${tabPrefix}请输入题目标题`)
    errors.value.title = '请输入题目标题'
  }

  if (!judgeForms.value[props.questionIndex].answer) {
    errorMessages.push(`${tabPrefix}请选择正确答案`)
    errors.value.answer = '请选择正确答案'
  }

  if (!judgeForms.value[props.questionIndex].difficulty) {
    errorMessages.push(`${tabPrefix}请选择难度系数`)
    errors.value.difficulty = '请选择难度系数'
  }

  return {
    valid: errorMessages.length === 0,
    errors: errorMessages
  }
}

const getFormData = () => {
  return {
    ...judgeForms.value[props.questionIndex]
  }
}

defineExpose({
  validate,
  getFormData
})

defineEmits(['add-question', 'remove-question'])
</script>

<style lang="scss" scoped>
.options-container {
  width: 100%;
}

.option-item {
  margin-bottom: 16px;

  .option-content {
    display: flex;
    align-items: stretch;

    .option-label {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      background-color: var(--el-fill-color-light);
      color: var(--el-text-color-regular);
      font-size: 14px;
      font-weight: 500;
      border: 1px solid var(--el-border-color);
      border-right: none;
      border-radius: 4px 0 0 4px;
    }

    .el-input {
      flex: 1;

      :deep(.el-input__wrapper) {
        border-radius: 0 4px 4px 0;
      }
    }
  }
}

:deep(.el-form-item) {
  margin-bottom: 22px;

  .el-form-item__label {
    font-weight: 500;
  }
}

:deep(.el-radio-group) {
  .el-radio {
    margin-right: 20px;
    margin-bottom: 8px;
  }
}

.error-message {
  color: var(--el-color-danger);
  font-size: 12px;
  margin-top: 4px;
  padding-left: 40px;
}

.required-label {
  :deep(.el-form-item__label) {
    &::before {
      content: '*';
      color: var(--el-color-danger);
      margin-right: 4px;
    }
  }
}

.header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: var(--el-text-color-primary);
  }
}
</style>
